<%@ page import="iNotes.assist.DataPool" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.text.DateFormat" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String status = (String) session.getAttribute("signIn");
    if (status == null || status.equals("false")) {
        response.sendRedirect("index.jsp");
        return;
    }
    int uid = (int) session.getAttribute("uid");
%>
<%
    //Get All the notes
    Connection connection = null;
    PreparedStatement pstmt1 = null;
    PreparedStatement pstmt2 = null;
    ResultSet rs = null;
    int[] noteId = null;
    String[] time = null;
    String[] content = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    int id = (int) session.getAttribute("uid");
    int cnt = 0;
    try {
        connection = DataPool.ds.getConnection();
        pstmt1 = connection.prepareStatement("select count(*) from user_note where user_id = ?");
        pstmt1.setInt(1, id);
        rs = pstmt1.executeQuery();
        if (rs.next())
            cnt = rs.getInt(1);
        if (cnt != 0) {
            try {
                pstmt2 = connection.prepareStatement("select note_id,add_time,content from user_note natural join note where user_id = ?");
                pstmt2.setInt(1, id);
                rs = pstmt2.executeQuery();
                noteId = new int[cnt];
                time = new String[cnt];
                content = new String[cnt];
                int ptr = 0;
                while (rs.next()) {
                    noteId[ptr] = rs.getInt(1);
                    time[ptr] = dateFormat.format(rs.getTimestamp(2));
                    content[ptr] = rs.getString(3);
                    ptr++;
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rs != null) rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (pstmt1 != null) pstmt1.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (pstmt2 != null) pstmt2.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
%>

<%
    //Get all share
    String[] senderName = null;
    int[] senderID = null;
    int[] source = null;
    int shareCnt = 0;
    try {
        pstmt1 = connection.prepareStatement("select count(*) from note_share where receiver_id = ?");
        pstmt1.setInt(1, id);
        rs = pstmt1.executeQuery();
        if (rs.next())
            shareCnt = rs.getInt(1);
        if (shareCnt != 0) {
            try {
                pstmt2 = connection.prepareStatement("select sender_id,username,source_id from note_share,user where receiver_id = ? and sender_id = uid");
                pstmt2.setInt(1, id);
                rs = pstmt2.executeQuery();
                senderName = new String[shareCnt];
                senderID = new int[shareCnt];
                source = new int[shareCnt];
                int ptr = 0;
                while (rs.next()) {
                    senderID[ptr] = rs.getInt(1);
                    senderName[ptr] = rs.getString(2);
                    source[ptr] = rs.getInt(3);
                    ptr++;
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rs != null) rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (pstmt1 != null) pstmt1.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (pstmt2 != null) pstmt2.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            if (connection != null) connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
%>
<html>
<head>
    <title>Notes of ${uname}</title>

    <!-- 最新版本的 JQuery 文件 -->
    <script src="https://code.jquery.com/jquery-3.6.0.js"></script>

    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
          integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <!-- 可选的 Bootstrap 主题文件（一般不用引入） -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css"
          integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous">

    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
            integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd"
            crossorigin="anonymous"></script>

    <!-- 对按钮添加操作 -->
    <script src="./js/formBtns.js"></script>
</head>
<body>

<h1>&nbsp;<div class="glyphicon glyphicon-list"></div>&nbsp;Notes of ${uname}&nbsp; <span class="badge"><%=cnt%></span>
</h1>

<div class="col-md-8 col-xs-12">
    <div class="alert alert-danger alert-dismissible" role="alert"
         style="display: <%=session.getAttribute("targetNotFound") == null ? "none" : "block"%>">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
        <strong>Error!</strong> Invalid username found.
    </div>
    <div class="alert alert-warning alert-dismissible" role="alert"
         style="display: <%=session.getAttribute("duplicatedNote") == null ? "none" : "block"%>">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
        <strong>Warning!</strong> Received duplicated note, or share has been canceled.
    </div>
    <div class="alert alert-warning alert-dismissible" role="alert"
         style="display: <%=session.getAttribute("duplicatedShare") == null ? "none" : "block"%>">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
        <strong>Warning!</strong> Shared the same note to the same user, share has been ignored.
    </div>
    <div class="alert alert-success alert-dismissible" role="alert"
         style="display: <%=session.getAttribute("shareTarget") == null ? "none" : "block"%>">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
        <strong>Success!</strong> Shared to ${shareTarget},waiting for acceptance. Delete the note before acceptance
        will cancel sharing.
    </div>
    <div style="display: <%=shareCnt <= 0 ? "none" : "block" %>">
        <%for (int i = 0; i < shareCnt; i++) { %>
        <div class="alert alert-success" role="alert" style="box-sizing: content-box">
            <strong>New Note!</strong> <%=senderName[i]%> want to share a note with you.
            <div class="btn-group" style="float: right;z-index: 0">
                <button type="button" class="btn btn-primary accept glyphicon glyphicon-ok" name="<%=senderID[i]%>,<%=source[i]%>">&nbsp;Accept
                </button>
                <button type="button" class="btn btn-danger dropdown-toggle glyphicon glyphicon-remove" data-toggle="dropdown"
                        aria-haspopup="true" aria-expanded="false">
                    &nbsp;Decline
                    <span class="caret"></span>
                    <span class="sr-only">Toggle Dropdown</span>
                </button>
                <ul class="dropdown-menu">
                    <li class="decline"><a href="#">Confirm to
                        Decline</a></li>
                </ul>
            </div>
            <button type="button" class="btn btn-primary accept" style="visibility: hidden">NoAction</button>


        </div>
        <%} %>
    </div>

    <%
        session.removeAttribute("targetNotFound");
        session.removeAttribute("duplicatedNote");
        session.removeAttribute("duplicatedShare");
        session.removeAttribute("shareTarget");
    %>
    <form class="form-inline" action="AddItem" method="post">
        <div class="form-group">
            <textarea class="form-control" cols="30" rows="4" name="content" id="content"
                      placeholder="New Content"></textarea>
        </div>
        <br>
        <br>
        <input style="display: none" name="_token" value="<%=session.getAttribute("_token")%>"/>
        <button type="submit" class="btn btn-success glyphicon glyphicon-plus">&nbsp;Add</button>
    </form>
    <form action="SignOut" method="get">
        <input style="display: none" name="_token" value="<%=session.getAttribute("_token")%>"/>
        <button type="submit" class="btn btn-warning glyphicon glyphicon-off">&nbsp;Logout</button>
    </form>

    <table class="table table-striped table-hover" style="display: <%=cnt == 0 ? "none" : "block"%>">
        <thead>
        <tr>
            <th class="col-xs-9">Content</th>
            <th class="col-xs-3">Control</th>
        </tr>
        </thead>
        <tbody>
        <%for (int i = 0; i < cnt; i++) { %>
        <tr>
            <td>

                <textarea class="form-control" rows="5" style="width: 100%;height: 100%"
                          readonly><%=URLDecoder.decode(content[i], "utf-8")%></textarea></td>
            <td>
                <div style="white-space: nowrap;font-size: 20px;margin: 10px;margin-left: 0;border: 1px solid black;border-radius: 10px;padding-left: 10px;padding-right: 10px;background-color: gainsboro"><%=time[i]%>
                </div>
                <button class="delBtn btn btn-danger glyphicon glyphicon-trash" name="<%=noteId[i]%>">&nbsp;Delete</button>
                <button class="shareBtn btn btn-info glyphicon glyphicon-share" name="<%=noteId[i]%>">&nbsp;Share</button>
            </td>
        </tr>
        <%} %>
        </tbody>
    </table>
</div>

<div style="display: none" id="csrftoken"><%=session.getAttribute("_token")%></div>
</body>
</html>
